<style scoped lang="less">
@import url(./upload.less);
</style>
<template>
  <div>
    <p class="input-zone">
      <slot></slot>
      <input type="file" name="file" value @change="upload" :multiple="multiple">
    </p>
    <div class="progress-wrapper" v-for="(file, index) in files" :key="index">
      <div class="content" style="display: flex;">
        <span
          :class="getIcon(file.primaryName)"
          class="iconfont"
          style="font-size:14px;margin-right:5px;left:5px"
        ></span>
        <div class="cont_middle">
          <span
            class="fileName"
            @click="scanFile(file.id, getSuffix(file.primaryName))"
          >{{file.primaryName}}</span>
          <span class="file_size">（大小:{{getFileSize(file.size)}}）</span>
          <span class="file_size download_file" @click="download(file.id,file.primaryName)">下载</span>
          <span
            class="animated slower"
            :class="{'fadeOut': file.widthValue === 100}"
            :style="{color:(file.widthValue === 100 ? 'green' : 'red')}"
          >{{file.widthValue ? file.widthValue + '%' : ''}}</span>
        </div>
        <span class="iconfont icon-shanchu icon" @click="deleteFile(index)"></span>
      </div>
      <div
        class="progress-progress animated slow"
        :class="{fadeOut:file.widthValue === 100}"
        :style="{ width: file.widthValue ? file.widthValue+'%' : 0}"
      ></div>
    </div>
    <template v-if="visible===true">
      <viewer :images="images">
        <img :src="imgPath" ref="imgp" width="100%" style="display:none">
      </viewer>
    </template>
  </div>
</template>

<script>
import fetch from '@/axios'
export default {
  props: {
    size: {
      default: 10,
      type: Number
    },
    fileType: {
      default: function () {
        return ['xls', 'xlsx']
      },
      type: Array
    },
    bucketName: {
      default: '',
      type: String
    },
    queryUrl: {
      default: '',
      type: String
    },
    correlationUuid: {
      default: '',
      type: String,
      required: true
    },
    delUrl: {
      default: '',
      type: String,
      required: true
    },
    downloadUrl: {
      default: '',
      type: String
    },
    scanUrl: {
      default: '',
      type: String
    },
    multiple: {
      default: false,
      type: Boolean
    },
    defaultList: {
      type: Array
    },
    uploadUrl: {
      default: '',
      type: String
    }
  },
  data () {
    return {
      files: [],
      visible: false,
      imgPath: '',
      spinShow: false
    }
  },
  mounted () {
    let _this = this
    fetch({
      url: `${_this.queryUrl}/${_this.correlationUuid}`,
      method: 'get'
    }).then(res => {
      let { data } = res
      if(Array.isArray(data) && data.length > 0) {
        _this.files = data
      }
    })
  },
  methods: {

    // 下载
    download (id, name) {
      let _this = this
      fetch({
        url: `${_this.downloadUrl}/${id}`,
        method: 'get',
        responseType: 'arraybuffer'
      }).then(res => {
        let blob = new Blob([res])
        let link = document.createElement('a')
        link.href = window.URL.createObjectURL(blob)
        link.download = name;
        link.click();
      })
    },
    // 预览图片
    scanFile (id, suffix) {
      if ('png,jpg,gif'.indexOf(suffix) === -1) return
      let _this = this
      _this.visible = true
      _this.spinShow = true
      fetch({
        url: `${_this.scanUrl}/${id}`,
        method: 'get'
      }).then(res => {
        _this.spinShow = false
        let { data } = res
        _this.imgPath = data
        _this.$refs.imgp.click()
      })
    },
    deleteFile (index) {
      let _this = this
      this.$Modal.confirm({
        title: '消息提示',
        content: '<p>你确认要删除吗</p>',
        onOk: () => {
          fetch({
            url: `${this.delUrl}/${this.files[index].id}`,
            method: 'delete'
          }).then(res => {
            let { code } = res
            if (code === 0) {
              _this.$Message.success('删除成功')
              _this.files.splice(index, 1)
            }
          })
        }
      })
    },
    find (list, name) {
      for (let i = 0; i < list.length; i++) {
        let current = list[i]
        for (let key in current) {
          if (name === current[key]) {
            return false
          }
        }
      }
    },
    getFileSize (fileByte) {
      var fileSizeByte = fileByte
      var fileSizeMsg = ''
      if (fileSizeByte < 1048576) fileSizeMsg = (fileSizeByte / 1024).toFixed(2) + 'KB'
      else if (fileSizeByte === 1048576) fileSizeMsg = '1MB'
      else if (fileSizeByte > 1048576 && fileSizeByte < 1073741824) fileSizeMsg = (fileSizeByte / (1024 * 1024)).toFixed(2) + 'MB'
      else if (fileSizeByte > 1048576 && fileSizeByte === 1073741824) fileSizeMsg = '1GB'
      else if (fileSizeByte > 1073741824 && fileSizeByte < 1099511627776) fileSizeMsg = (fileSizeByte / (1024 * 1024 * 1024)).toFixed(2) + 'GB'
      else fileSizeMsg = '超过1TB'
      return fileSizeMsg
    },
    getIcon (fileName) {
      switch (this.getSuffix(fileName)) {
        case 'doc':
        case 'docx':
          return 'icon-Word'
        case 'xls':
        case 'xlsx':
          return 'icon-Excel'
        case 'ppt':
        case 'pptx':
          return 'icon-PPT'
        case 'zip':
        case 'rar':
          return 'icon-geshi_yasuobaotar'
        default:
          return 'icon-tupian1'
      }
    },
    getSuffix (fileName) {
      if (fileName) {
        let suffixs = fileName.split('.')
        return fileName.split('.')[suffixs.length - 1]
      }
    },
    upload (e) {
      var vm = this
      let files = e.target.files
      if (!this.multiple && this.files.length === 1) {
        this.$Message.error('不支持多个文件')
        return
      }
      for (let i = 0; i < files.length; i++) {
        let file = files[i]
        let fileName = file.name
        // 判断是否支持此格式文件
        if (vm.fileType.indexOf(vm.getSuffix(fileName)) === -1) {
          this.$Message.error('不支持此格式的文件')
          return
        }
        // 判断文件是否大于指定的大小
        if ((file.size / (1024 * 1024)) > vm.size) {
          this.$Message.error('上传文件超过限定的大小')
          return
        }
        // 判断是否重复上传文件
        if (vm.find(vm.files, fileName) === false) {
          this.$Message.error('此文件已上传')
          return
        }
        // 上述没有问题直接执行一下流程
        let obj = {
          size: file.size,
          primaryName: fileName,
          widthValue: 0
        }
        vm.files.push(obj)
        let formData = new FormData()
        formData.append('file', file)
        formData.append('correlationUuid', vm.correlationUuid)
        formData.append('bucketName', vm.bucketName)
        fetch({
          url: vm.uploadUrl,
          method: 'post',
          data: formData,
          headers: { 'Content-Type': 'multipart/form-data' },
          onUploadProgress: function (e) {
            if (e.lengthComputable) {
              let rate = vm.uploadRate = e.loaded / e.total
              if (rate < 1) {
                obj.primaryName = fileName
                obj.widthValue = (rate * 100).toFixed(2)
              }
            }
          }
        }).then(res => {
          obj.primaryName = fileName
          let { code, msg, data: { fileid } } = res
          if (code === 0) {
            obj.widthValue = 100
            obj.id = fileid
            vm.$set(vm.files, vm.files.length - 1, obj)
          } else {
            vm.$Message.warning(msg)
          }
        })
      }
    }
  }
}
</script>
